package yxy.game.pm2.command.kow;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.KowMessage;
import yxy.game.pm2.module.kow.KowHandle.KowStepEnum;
import yxy.game.pm2.module.kow.KowModule;
import yxy.game.pm2.module.kow.RankKowGroup;
import yxy.game.pm2.module.player.PlayerHandle;

/** 天下第一 天下第一小组赛组信息 */
@MessageType(proto = Command.KowGroupInfo, classtype = KowMessage.KowGroupInfoRequest.class)
public class CMD_KowGroupInfo extends Command<KowMessage.KowGroupInfoRequest> {

	@Override
	public void execute(MessageSource messageSource, KowMessage.KowGroupInfoRequest request) {
		String playerCode = messageSource.getTag();
		int group = request.getGroup();

		KowMessage.KowGroupInfoResponse.Builder response = KowMessage.KowGroupInfoResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

		KowModule kowModule = KowModule.get(areaBean.getGroupId());
		if (kowModule.getState().equals(KowStepEnum.STEP_PRE)) {
			send(messageSource, response, Result.KowNoGroup);// 尚未分组
			return;
		}

		if (group < 1 || group > 8) {
			send(messageSource, response, Result.ParamError);
			return;
		}
		RankKowGroup rankKowGroup = new RankKowGroup(areaBean.getGroupId(), group);

		int rank = 1;
		for (RankEntry entry : rankKowGroup.range(1, 0)) {
			String code = entry.getKey();
			long score = entry.getValue();
			KowMessage.KowPlayer.Builder builder = KowMessage.KowPlayer.newBuilder();
			builder.setGroupRank(rank++);
			builder.setGroupScore(score);
			builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(code));
			response.addPlayers(builder);
		}
		response.setGroup(group);
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, KowMessage.KowGroupInfoResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}